#!/bin/bash

ARGS=()
MO='true'
TIMEOUT="60"
while [[ $# -gt 0 ]]; do
case "$1" in
    -algorithm)
        ALGO="$2"
        shift; shift
        ;;
    --MO)
        MO="$2"
        shift; shift
        ;;
    *)
        ARGS+=("$1")
        shift
        ;;
esac
done

function hmean {
    [[ $1 =~ \[(.*),[[:space:]](.*)\] ]]
    hm=$(python -c "print((lambda x,y: 1 if x == 1 or y == 1 else 1-(2/((1-x)**-1 + (1-y)**-1)))(${BASH_REMATCH[1]}, ${BASH_REMATCH[2]}))")
    [[ $1 =~ (.*)\[.*\](.*) ]]
    res="${BASH_REMATCH[1]}0, ${hm}${BASH_REMATCH[2]}"
    echo "${res/Result/Result of this algorithm run}"
}

DATA=$(tr ":" " "<<<"${ARGS[0]}")
TIMEOUT="${ARGS[2]}"
SEED="${ARGS[4]}"
ARGS=${ARGS[*]:5}
CMD="../algorithms/${ALGO//[\'\"]/} -data $DATA -seed $SEED ${ARGS//[\'\"]/}"

ret="$(timeout -s2 $TIMEOUT $CMD)"
if [ $? -ne 0 ]; then
    ret="Result: TIMEOUT, ${TIMEOUT}, [1.0001, 1.0001], 0"
fi

if [[ $MO == 'true' ]]; then
    echo "$ret"
else
    hmean "$ret"
fi
